module.exports = (app) => {
  const express = require("express");
  const path = require("path");
  const jwt = require("jsonwebtoken");
  const assert = require("http-assert");
  const AdminUser = require("../../models/AdminUser");

  // 让子路由能继承父路由的参数 mergeParams: true
  const router = express.Router({ mergeParams: true });

  // 创建资源
  router.post("/", async (req, res) => {
    // 为 req.Model 集合添加数据
    const model = await req.Model.create(req.body);
    res.send(model);
  });
  // 资源列表
  router.get("/", async (req, res) => {
    const queryOptions = {};
    if (req.Model.modelName === "Category") {
      queryOptions.populate = "parent";
    }
    // 查找关联模型的数据
    // const items = await Model.find().populate("parent").limit(10);
    const items = await req.Model.find().setOptions(queryOptions).limit(100);
    // console.log(req.Model, req.Model.modelName);
    res.send(items);
  });
  // 根据 _id 获取资源 资源详情
  router.get("/:id", async (req, res) => {
    const model = await req.Model.findById(req.params.id);
    res.send(model);
  });
  // 更新资源
  router.put("/:id", async (req, res) => {
    // console.log(req);
    const model = await req.Model.findByIdAndUpdate(req.params.id, req.body);
    res.send(model);
  });
  // 删除资源
  router.delete("/:id", async (req, res) => {
    // console.log(req);
    await req.Model.findByIdAndDelete(req.params.id);
    res.send({
      success: true,
    });
  });

  // 登录校验中间件
  const authMiddleware = require("../../middleware/auth");

  // 获取模型中间件
  const resourceMiddleware = require("../../middleware/resource");
  app.use(
    "/admin/api/rest/:resource",
    authMiddleware(),
    resourceMiddleware(),
    router
  );

  // 使用 multer 来上传图片
  const multer = require("multer");
  // const upload = multer({ dest: __dirname + "../../uploads" });
  const upload = multer({ dest: path.join(__dirname, "../../uploads") });
  // file和前端传过来的名一致
  app.post(
    "/admin/api/upload",
    authMiddleware(),
    upload.single("file"),
    async (req, res) => {
      const file = req.file;
      file.url = `http://localhost:3000/uploads/${file.filename}`;
      // console.log(__dirname);
      res.send(file);
    }
  );

  // 用户登录接口
  app.post("/admin/api/login", async (req, res) => {
    const { username, password } = req.body;
    // 1.根据用户名来找用户
    // 模型里加了 select: false 默认为选取不到
    // 前缀 + 为强制选择   - 为排除选择  +password 强制选择 password
    const user = await AdminUser.findOne({ username }).select("+password");
    assert(user, 422, "用户不存在");
    /*  if (!user) {
      return res.status(422).send({
        message: "用户不存在",
      });
    } */
    // 2.校验密码
    const isValid = require("bcrypt").compareSync(password, user.password);
    assert(isValid, 422, "密码错误");
    /* if (!isValid) {
      return res.status(422).send({
        message: "密码错误",
      });
    } */
    // 3.返回 token  安装 jsonwebtoken 来做token验证
    const token = jwt.sign({ id: user._id }, app.get("secret"));
    // console.log(token);
    res.send({ token });
  });

  // 错误处理函数
  app.use((err, req, res, next) => {
    res.status(err.status || 500).send({
      message: err.message,
    });
  });
};
